//wxjsdk 接入
// 获取jsapi_ticket的接口 
//正常是直接请求https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi，但是我这有跨域，就叫后端写了个接口帮我请求
import { getTicket } from "@/api/common";
import wx from 'weixin-js-sdk';
// 加密插件
import CryptoJS from 'crypto-js'
// 配置文件
import config from "@/config";
//是否是微信浏览器
const isWechat = () => {
	var ua = window.navigator.userAgent.toLowerCase()
	if (ua.match(/micromessenger/i) == 'micromessenger') {
		return true;
	} else {
		return false;
	}
}
// 生成随机字符
function randomString(len) {
	len = len || 32;
	var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
	var maxPos = $chars.length;
	var pwd = '';
	for (let i = 0; i < len; i++) {
		pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
}

//需要使用的JS接口列表
let jsApiList = [
	'checkJsApi',
	'getLocation',
	'openLocation',
	'wx-open-launch-app',
	'wx-open-launch-weapp'
]

export default {
	isWechat,
	//配置信息
	initJssdk: () => {
		return new Promise((resolve, reject) => {
			//获取界面url
			let url = window.location.href.split('#')[0]
			getTicket().then(res => {
				let { ticket } = res.result
				let timestamp = Math.round(new Date().getTime() / 1000).toString() // 时间戳
				let nonceStr = randomString()  // 随机字符
				let signature = CryptoJS.SHA1(`jsapi_ticket=${ticket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${url}`).toString()
				wx.config({
					debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来
					appId: config.appId, // 必填，公众号的唯一标识
					timestamp, // 必填，生成签名的时间戳
					nonceStr, // 必填，生成签名的随机串
					signature,// 必填，签名
					jsApiList, // 必填，需要使用的JS接口列表
					openTagList:['wx-open-launch-weapp']
				});
				resolve()
			}).catch(err=>{
				reject(err)
			})
		})
	},
	// 检查权限,  这里是使用回调,  _option里面有success和fail参数, 当checkJsApi调用成功是 调用_option.success, 反之_option.fail
	checkJsApi: function (_option = {}) {
		jweixin.checkJsApi({
			jsApiList,
			success: res => {
				console.log(JSON.stringify(res))
			},
			fail: res => {
				console.log(JSON.stringify(res))
			},
		})
	},
	ready:wx.ready,
	// 获取位置信息
	getLocation: wx.getLocation,
	openLocation: wx.openLocation,
	// aa:function(){
	// 	console.log(wx.openLocation)
	// }
}
